<?php
namespace app\admin\controller\system;


use app\admin\model\SystemConfig;
use app\admin\service\TriggerService;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Cache;

/**
 * @ControllerAnnotation(title="系统配置管理")
 * Class Config
 * @package app\admin\controller\system
 */
class Config extends AdminController
{

    public function __construct(App $app)
    {
        parent::__construct($app);
        parent::initialize();
        $this->model = new SystemConfig();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="上传配置")
     */
    public function upload()
    {
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="邮件配置")
     */
    public function mail()
    {
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="短信配置")
     */
    public function sms()
    {
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="聚合数据配置")
     */
    public function juhe()
    {
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="功能开关")
     */
    public function switch()
    {
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="支付配置")
     */
    public function payment()
    {
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="SEO配置")
     */
    public function seo()
    {
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="保存")
     */
    public function save()
    {
        $this->isDemo && $this->error('演示环境下不允许修改');
        $post = $this->request->post();
        try {
            $name=$post['field'];
            if(isset($post['select'])){
                unset($post['select']);
            }
            if(isset($post['file'])){
                unset($post['file']);
            }

            $data['value'] = json_encode($post);
            $row = $this->model->where('name', $name)->find();
            if ($row) {
                $row->save($data);
            } else {
                $data['name'] = $name;
                $this->model->save($data);
            }
            TriggerService::updateMenu();
            TriggerService::updateSysconfig();
        } catch (\Exception $e) {
            $this->error('保存失败');
        }
        $this->success('保存成功');
    }

    function setEnv(){
        $post = $this->request->post();
        setEnv($post['field'],$post['value']);
        if($post['field']=='key'){
            Cache::clear();
        }
        $this->success('设置成功');
    }
}